//
//  DataBase.m
//  BreadTravel
//
//  Created by 张健 on 16/1/4.
//  Copyright © 2016年 蓝鸥科技. All rights reserved.
//

#import "DataBase.h"

@implementation DataBase

+ (instancetype)shareDataBase{
    
    static DataBase *dataBase = nil;
    if (dataBase == nil) {
        dataBase = [[DataBase alloc]init];
    }
    return dataBase;
}

-(void)openDB
{
    //导入sqlite框架，导入FMDB文件夹
    
    //1.获得数据库文件的路径
    NSString *fileName=[DOCUMENTPATH stringByAppendingPathComponent:@"user.sqlite"];
    NSLog(@"fileName = %@",fileName);
    
    //2.获得数据库
    self.db = [FMDatabase databaseWithPath:fileName];
    
    //3.打开数据库
    if ([self.db open]) {
        NSLog(@"打开成功");
    }else{
        NSLog(@"打开失败");
    }
}

//创建user表
- (void)createUserTable{
    
    BOOL result=[self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS user (number INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, password TEXT NOT NULL, headImage TEXT NOT NULL);"];
    
    if (result) {
        NSLog(@"user创表成功");
    }else{
        NSLog(@"user创表失败");
    }
}

//插入数据
- (void)insertUser:(NSString *)name password:(NSString *)password headImage:(NSData *)headImage{
    
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO user(name, password, headImage) VALUES('%@', '%@', '%@')", name, password, headImage];
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"插入user成功");
    }else{
        NSLog(@"插入user失败");
    }
}
//删除表
-(void)dropTable{
    
    NSString *sql = [NSString stringWithFormat:@"DROP TABLE IF EXISTS user"];
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"删除表成功");
    }else{
        NSLog(@"删除表失败");
    }
}
//查询
-(NSMutableArray *)selectUserData:(NSString *)name{
    
    NSMutableArray *array = [NSMutableArray array];
    //1.执行查询语句
    FMResultSet *resultSet = [self.db executeQuery:[NSString stringWithFormat:@"select * from user WHERE name = '%@'", name]];
    
    //2.遍历结果集合
    while ([resultSet next]) {
        
        NSInteger number = [resultSet intForColumn:@"number"];
        NSString *name = [resultSet objectForColumnName:@"name"];
        NSString *password = [resultSet objectForColumnName:@"password"];
        NSData *data = [resultSet objectForColumnName:@"headImage"];
        
        MineUserModel *user = [[MineUserModel alloc]init];
        user.number = number;
        user.name = name;
        user.password = password;
        user.data = data;
        
        [array addObject:user];
    }
    return array;
}


@end
